package com.chao.utils;


import com.chao.pojo.Content;
import com.chao.service.ContentService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        // new HtmlParseUtil().parseJD("短袖").forEach(System.out::println);
        // new ContentService().parseContent("vue");
        String keywords = "超哥";
        // %E8%B6%85%E5%93%A5
        System.out.println(keywords);
        keywords = URLEncoder.encode(keywords,"utf-8");
        System.out.println(keywords);
    }

    public List<Content> parseJD(String keywords) throws IOException {
        // 获取请求 https://search.jd.com/Search?keyword=java
        // 前提，需要联网，不能获取ajax数据！
        // String enc="&enc=utf-8";

        // 解析keywords中的
        keywords = URLEncoder.encode(keywords,"utf-8");
        System.out.println("keywords"+keywords);
        // String enc = "?enc=utf-8";

        String url = "https://search.jd.com/Search?keyword=" + keywords;
        // 解析网页 Jsoup返回Document就是浏览器Document对象

        // Document document = Jsoup.parse(new URL(url).openStream(),"utf-8",url);
        Document document = Jsoup.parse(new URL(url),30000);
        // System.out.println(document);
        Element element = document.getElementById("J_goodsList");

        // 获取所有的li元素
        Elements elements = element.getElementsByTag("li");

        ArrayList<Content> goodsList = new ArrayList<>();
        // 获取元素中的内容
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            Content content = new Content();
            content.setTitle(title);
            content.setPrice(price);
            content.setImg(img);
            goodsList.add(content);
        }
        return goodsList;
    }

}
